﻿@page "/system/user"
@attribute [ReuseTabsPage(Title = "用户管理")]

<Spin Spinning="Loading">
    <Table @ref="_Table"
           AutoHeight
           TItem="SystemUser"
           @bind-PageSize="Ps"
           @bind-PageIndex="Pi"
           Total="Total"
           DataSource="DataSource"
           @bind-SelectedRows="SelectedRows"
           ScrollX="1300"
           OnChange="OnChange">
        <TitleTemplate>
            <Flex Justify="FlexJustify.Start" Gap="@("10")">
                <Input Width="300" Placeholder="输入名称" @bind-Value="@Q_Account" />
                <Button OnClick="Search">搜索</Button>
                <Button OnClick="ResetQuery">重置</Button>

                <Button Type="ButtonType.Primary" Color="Color.Green6" OnClick="() => StartEdit(default)">新增</Button>
            </Flex>
        </TitleTemplate>
        <ColumnDefinitions Context="row">
            <PropertyColumn Align="ColumnAlign.Center" Property="c=>c.Id" Width="100" Title="ID" />
            <PropertyColumn Align="ColumnAlign.Center" Property="c=>c.Avatar" Width="100" Title="头像">
                <Image Src="@row.Avatar" Fallback="" />
            </PropertyColumn>
            <PropertyColumn Align="ColumnAlign.Center" Property="c=>c.Account" Width="200" Title="用户名" />
            <PropertyColumn Property="c=>c.NickName" Width="300" Title="用户信息">
                昵称：@row.NickName
                <br />
                手机：@row.Mobile
                <br />
                邮箱：@row.Email
            </PropertyColumn>
            <PropertyColumn Align="ColumnAlign.Center" Width="100" Property="c=>c.RoleName" Title="角色" />
            <PropertyColumn Align="ColumnAlign.Center" Width="100" Property="c=>c.DepartmentName" Title="部门" />
            <PropertyColumn Align="ColumnAlign.Center" Width="100" Property="c=>c.Enabled" Title="是否启用">
                <Switch Checked="@row.Enabled" @bind-Value="@row.Enabled" CheckedChildren="启用" UnCheckedChildren="禁用" OnChange="() => CheckedChanged(row)" />
            </PropertyColumn>
            <PropertyColumn Align="ColumnAlign.Center" Property="c => c.CreateTime" Width="200" Title="创建时间">
                @{
                    var formattedTime = row.CreateTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "N/A";
                }
                @formattedTime
            </PropertyColumn>
            <PropertyColumn Align="ColumnAlign.Center" Width="250" Property="c=>c.Area" Title="地区" />
            <PropertyColumn Align="ColumnAlign.Center" Width="250" Property="c=>c.Signature" Title="签名" />
            <ActionColumn Width="180" Title="操作" Fixed="ColumnFixPlacement.Right">
                <Button Type="ButtonType.Primary" Color="Color.Blue6" OnClick="() => StartEdit(row)">编辑</Button>
                <Button Type="ButtonType.Primary" Color="Color.Red6" Danger OnClick="() => Delete(row)">删除</Button>
            </ActionColumn>
        </ColumnDefinitions>
        <PaginationTemplate>
            <Pagination Class="@(context.PaginationClass + " my-custom-pagination")"
                        Total="context.Total"
                        PageSize="context.PageSize"
                        Current="context.PageIndex"
                        ShowSizeChanger
                        ShowQuickJumper
                        ShowTotal="ShowTotal"
                        OnChange="context.HandlePageChange" />
        </PaginationTemplate>
    </Table>
</Spin>

@inject ModalService ModalService;
@inject ConfirmService ComfirmService;
@inject IMessageService MessageService;

@code {

    // <FormItem Label="用户类型" Required>
    //     <Select @bind-Value="@context.UserType"
    //             TItemValue="UserType"
    //             TItem="string"
    //             DefaultActiveFirstOption="true">
    //         <SelectOptions>
    //             @foreach (var userType in Enum.GetValues(typeof(UserType)).Cast<UserType>())
    //         {
    //             <SelectOption TItemValue="UserType" TItem="string" Value="@userType" Label="@userType.Description()" />
    //         }
    //         </SelectOptions>
    //     </Select>
    // </FormItem>

    private void StartEdit(SystemUser row)
    {
        var data = row ?? new();
        ModalRef<bool> modalRef = default;
        IForm form = default;
        modalRef = ModalService.CreateModal<bool>(new()
                {
                    DestroyOnClose = true,
                    MaskClosable = false,
                    Title = data.Id > 0 ? "编辑" : "新增",
                    Content =
    @<Form @ref="form" Model="data" OnFinish="()=> modalRef.OkAsync(true)" LabelColSpan="6" WrapperColSpan="18">
        @if (data.Id == 0)
    {
        <FormItem Label="用户名" Required>
            <Input @bind-Value="@data.Account" />
        </FormItem>
        <FormItem Label="密码" Required>
            <InputPassword @bind-Value="@data.Password" />
        </FormItem>
        <FormItem Label="确认密码" Required>
            <InputPassword @bind-Value="@data.ConfirmPassword" />
        </FormItem>
    }
        <FormItem Label="昵称" Required>
            <Input @bind-Value="@data.NickName" />
        </FormItem>
        <FormItem Label="手机" Required>
            <Input @bind-Value="@data.Mobile" />
        </FormItem>
        <FormItem Label="邮箱">
            <Input @bind-Value="@data.Email" />
        </FormItem>
        <FormItem Label="角色" Required>
            <Select @bind-Value="@data.RoleId"
                    TItemValue="long"
                    TItem="string"
                    DefaultActiveFirstOption="true" EnableSearch AllowClear>
                <SelectOptions>
                    @foreach (var role in Roles)
                {
                    <SelectOption TItemValue="long" TItem="string" Value="@role.Id" Label="@role.Name" />
                }
                </SelectOptions>
            </Select>
        </FormItem>
        <FormItem Label="部门" Required>
            <Select @bind-Value="@data.DepartmentId"
                    TItemValue="long"
                    TItem="string"
                    DefaultActiveFirstOption="true" EnableSearch AllowClear>
                <SelectOptions>
                    @foreach (var department in Departments)
                {
                    <SelectOption TItemValue="long" TItem="string" Value="@department.Id" Label="@department.Name" />
                }
                </SelectOptions>
            </Select>
        </FormItem>
        <FormItem Label="是否启用" Required>
            <Select @bind-Value="@data.Enabled"
                    TItemValue="bool"
                    TItem="string"
                    DefaultActiveFirstOption="false">
                <SelectOptions>
                    <SelectOption TItemValue="bool" TItem="string" Value="true" Label="启用" />
                    <SelectOption TItemValue="bool" TItem="string" Value="false" Label="禁用" />
                </SelectOptions>
            </Select>
        </FormItem>
        <FormItem Label="地区">
            <Cascader Options="@Areas" @bind-Value="@data.LastAreadId" SelectedNodesChanged="OnChange" />
        </FormItem>
        <FormItem Label="地址">
            <Input @bind-Value="@data.Address" />
        </FormItem>
        <FormItem Label="签名">
            <TextArea ShowCount MaxLength="200" @bind-Value="@data.Signature" />
        </FormItem>
    </Form>,
            OnOk = async (e) =>
            {
                if (!form.Validate())
                {
                    return;
                }

                modalRef.SetConfirmLoading(true);

                var flag = await InsertOrUpdate(data);
                if (flag)
                {
                    MessageService.Success("操作成功");
                    await modalRef.CloseAsync();
                    _Table.ReloadData(Pi, Ps);
                    StateHasChanged();
                }
                else
                {
                    MessageService.Error("操作失败");
                }

                modalRef.SetConfirmLoading(false);
            },
            OnCancel = async (e) =>
            {
                if (form.IsModified && (!await Comfirm("已修改内容，确定退出吗?")))
                {
                    return;
                }
                await modalRef.CloseAsync();
            }
        });
    }

    private async Task<bool> Comfirm(string message)
    {
        return await ComfirmService.Show(message, "提示", ConfirmButtons.YesNo, ConfirmIcon.Warning) == ConfirmResult.Yes;
    }
}
